package cn.songtx.iot.service.impl;

import cn.songtx.iot.mapper.SysFamilyMapper;
import cn.songtx.iot.mapper.SysRoomMapper;
import cn.songtx.iot.pojo.SysFamily;
import cn.songtx.iot.pojo.SysRoom;
import cn.songtx.iot.service.ISysRoomService;
import cn.songtx.iot.vo.FamilyRoomVO;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@DS("master")
public class SysRoomServiceImpl extends ServiceImpl<SysRoomMapper, SysRoom> implements ISysRoomService {

    @Autowired
    SysFamilyMapper sysFamilyMapper;

    // 自定义的Service接口,根据userId查询嵌套结构的FamilyRoom数组
    @Override
    public List<FamilyRoomVO> selectFamilyRoomListByUserId(Long sysUserId) {
        // 1. 根据userId查询sys_family表,返回是个list,长度可能是0,1,或者多
        LambdaQueryWrapper<SysFamily> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysFamily::getSysUserId, sysUserId);
        List<SysFamily> list = sysFamilyMapper.selectList(lambdaQueryWrapper);

        // 2.PO->VO,增强for
        List<FamilyRoomVO> familyRoomVOS = new ArrayList<>();
        for (SysFamily sysFamily : list) {
            FamilyRoomVO familyRoomVO = new FamilyRoomVO();
            BeanUtils.copyProperties(sysFamily, familyRoomVO);
            familyRoomVOS.add(familyRoomVO);
        }

        // 3.从返回的对象中获取id,stream的map操作
        List<Long> ids = list.stream().map(SysFamily::getId).toList();

        // 4.根据familyId查询sys_room表,返回list,顺序为该表的主键id
        LambdaQueryWrapper<SysRoom> sysRoomLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysRoomLambdaQueryWrapper.in(SysRoom::getFamilyId, ids);
        List<SysRoom> roomList = this.list(sysRoomLambdaQueryWrapper);

        // 5.按照查询的familyId分组
        Map<Long, List<SysRoom>> collect = roomList.stream().collect(Collectors.groupingBy(SysRoom::getFamilyId));

        // 6.分组后的数据拼接
        for (FamilyRoomVO familyRoomVO : familyRoomVOS) {
            familyRoomVO.setRooms(collect.get(familyRoomVO.getId()));
        }

        return familyRoomVOS;
    }
}
